<template>
  <div class="player" v-show="playlist.length>0" >
    <transition name="normal" @enter="enter" @after-enter="afterEnter" @leave="leave" @after-leave="afterLeave">
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.image" width="100%" height="100%" alt="">
        </div>
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
        </div>
        <div class="middle" @touchstart="middleTouchStart" @touchmove="middleTouchMove" @touchend="middleTouchEnd">
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <img class="image" :src="currentSong.image" alt="">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <scroll ref="lyricList" class="middle-r" :data="currentLyric&&currentLyric.line">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine" 
                class="text"
                :class="{'current': currentLineNumber === index}"
                v-for="(line, index) in currentLyric.lines" :key="index"
                >{{line.txt}}</p>
              </div>
            </div>
          </scroll>
        </div>
        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{'active': currentShow === 'cd'}"></span>
            <span class="dot" :class="{'active': currentShow === 'lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{format(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"></progress-bar>
            </div>
            <span class="time time-r">{{format(currentSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon icon-left" @click="changeMode">
              <i :class="iconMode"></i>
            </div>
            <div class="icon icon-left" :class="disableCls">
              <i @click="prev" class="icon-prev"></i>
            </div>
            <div class="icon icon-center" :class="disableCls">
              <i @click="togglePlaying" :class="playIcon"></i>
            </div>
            <div class="icon icon-right" :class="disableCls">
              <i @click="next" class="icon-next"></i>
            </div>
            <div class="icon icon-right">
              <i @click="toggleFavorite(currentSong)" class="icon" :class="getFavoriteIcon(currentSong)"></i>
            </div>
          </div>
        </div>
      </div>

    </transition>
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open">
        <div class="icon">
          <div class="imgWrapper">
            <img :class="cdCls" :src="currentSong.image" width="40" height="40"/>
          </div>
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <span class="desc" v-html="currentSong.singer"></span>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i @click.stop.prevent="togglePlaying" class="icon-mini" :class="miniIcon"></i>
          </progress-circle>
        </div>
        <div class="control" @click.stop="showPlaylist">
          <i class="icon-playlist"></i>
        </div>
      </div>
    </transition>
    <playlist ref="playlist"></playlist>
    <audio ref="audio" :src="currentSong.url" @play="ready" @error="error" @timeupdate="updateTime" @ended="end"></audio>
  </div>
</template>
<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import animations from 'create-keyframe-animation'
import { prefixStyle } from 'common/js/dom'
import progressBar from 'base/progress-bar/progress-bar'
import progressCircle from 'base/progress-circle/progress-circle'
import { playMode } from 'common/js/config'
import Lyric from 'lyric-parser'
import scroll from 'base/scroll/scroll'
import playlist from 'components/playlist/playlist'
import { playerMixin } from 'common/js/mixin'

const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')

export default {
  mixins: [playerMixin],
  data() {
    return {
      // 音乐加载的状态
      songReady: false,
      // 当前播放的时间
      currentTime: 0,
      // 记录播放时间和歌曲总时长的比例
      percent: 0,
      radius: 32,
      // 当前歌词对象
      currentLyric: null,
      // 当前歌词的行数
      currentLineNumber: 0,
      // 当前在cd旋转界面还是歌词界面
      currentShow: 'cd',
      // 当前哪一行的歌词
      playingLyric: ''
    }
  },
  computed: {
    ...mapGetters([
      'fullScreen',
      'playing',
      'playlist',
      'playing',
      'currentIndex'
    ]),
    // 根据播放状态来确定歌曲图片是否可以旋转
    cdCls() {
      return this.playing ? 'play' : 'play pause'
    },
    // 根据播放状态来确定normal播放器的图标
    playIcon() {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    // 根据播放状态来确定mini播放器的图标
    miniIcon() {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    // 根据歌曲是否加载好来确定按钮能不能点击
    disableCls() {
      return this.songReady ? '' : 'disable'
    }
  },
  created() {
    // 记录触摸的位置，因为不需要监听数据的变化，所以不用添加到data
    this.touch = {}
  },
  methods: {
    // 显示播放列表
    showPlaylist() {
      this.$refs.playlist.show()
    },
    // 返回按钮
    back() {
      this.setFullScreen(false)
    },
    // 打开播放器
    open() {
      this.setFullScreen(true)
    },
    enter(el, done) {
      const { x, y, scale } = this._getPosAndScale()

      // 先定义一个动画
      let animation = {
        0: {
          transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
        },
        60: {
          transform: `translate3d(0,0,0) scale(1.1)`
        },
        100: {
          transform: `translate3d(0,0,0) scale(1)`
        }
      }
      // 注册这个动画
      animations.registerAnimation({
        name: 'move',
        animation,
        presets: {
          duration: 400,
          easing: 'linear'
        }
      })
      // 运行动画
      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter() {
      // 注销动画
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave(el, done) {
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const { x, y, scale } = this._getPosAndScale()
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave() {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },
    // 得到动画的起始位置
    _getPosAndScale() {
      let targetWidth = 40
      let width = window.innerWidth * 0.8
      let scale = targetWidth / width
      let paddingTop = 80
      let paddingBottom = 30
      let paddingLeft = 40
      let x = -(window.innerWidth / 2 - paddingLeft)
      let y = window.innerHeight - paddingTop - width / 2 - paddingBottom
      return {
        x,
        y,
        scale
      }
    },
    // 切换播放状态
    togglePlaying() {
      this.setPlayingState(!this.playing)
      // 让歌词切换
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    // 播放上一首
    prev() {
      // 当这首音乐没有加载完成不可以点击上一首
      if (!this.songReady) {
        return
      }
      if (this.playlist.length === 1) {
        this.loop()
        return
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }
        this.setCurrentIndex(index)
        // 播放上一首时，playing的状态也应该变化,如果是false，应该变为true
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    // 播放下一首
    next() {
      // 当这首音乐没有加载完成不可以点击下一首
      if (!this.songReady) {
        return
      }
      // 当列表为1的时候，currentIndex没有变化，也就是currentSong没有变化
      if (this.playlist.length === 1) {
        this.loop()
        return
      } else {
        let index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        // 播放下一首时，playing的状态也应该变化,如果是false，应该变为true
        if (!this.playing) {
          this.togglePlaying()
        }
      }
      this.songReady = false
    },
    // 当音乐加载好的时候
    ready() {
      this.songReady = true
      // 保存播放历史
      this.savePlayHistory(this.currentSong)
    },
    // 当音乐加载错误的时候
    error() {
      this.songReady = true
    },
    // 当audio播放时间发生变化会调用这个方法
    updateTime(e) {
      this.currentTime = e.target.currentTime // 调用audio的方法获取时间
      this.percent = this.currentTime / this.currentSong.duration
    },
    // 格式化时间
    format(time) {
      // time | 0 表示向下取整，相当于调用Math.floor()
      time = time | 0
      let minute = time / 60 | 0
      let second = time % 60
      second = this._pad(second)
      return `${minute}:${second}`
    },
    // 对一个数值前面补0
    _pad(num, n = 2) {
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    // 当子组件的进度条发生改变触发这个事件 
    onProgressBarChange(percent) {
      const currentTime = this.currentSong.duration * percent
      this.$refs.audio.currentTime = currentTime
      // 让播放器再次播放
      if (!this.playing) {
        this.togglePlaying()
      }
      // 让歌词跳到播放地址
      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },

    // 当歌曲播放结束的时候,如果循环播放就再次播放这一首
    end() {
      if (this.mode === playMode.loop) {
        this.loop()
      } else {
        this.next()
      }
    },
    // 循环播放
    loop() {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
      this.setPlayingState(true)
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    // 获取歌词数据
    getLyric() {
      this.currentSong.getLyric().then((lyric) => {
        if (this.currentSong.lyric !== lyric) {
          return
        }
        this.currentLyric = new Lyric(lyric, this.handleLyric)
        if (this.playing) {
          this.currentLyric.play()
        }
      }).catch(() => {
        this.currentLyric = null
        this.playingLyric = ''
        this.currentLineNumber = 0
      })
    },
    // 当歌词播放的时候行数改变的回调函数
    handleLyric({ lineNum, txt }) {
      // 拿到当前行数
      this.currentLineNumber = lineNum
      this.playingLyric = txt
      if (lineNum > 5) {
        let linEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(linEl, 1000)
      } else {
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
    },
    middleTouchStart(e) {
      this.touch.initiated = true
      this.touch.moved = false
      let touch = e.touches[0]
      this.touch.startX = touch.pageX
      this.touch.startY = touch.pageY
    },
    middleTouchMove(e) {
      if (!this.touch.initiated) {
        return
      }
      let touch = e.touches[0]
      let deltaX = touch.pageX - this.touch.startX
      let deltaY = touch.pageY - this.touch.startY
      // 如果纵轴的增量大于横轴的增量，则认定为歌词的滚动界面，不操作
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        return
      }
      if (!this.touch.moved) {
        this.touch.moved = true
      }
      let left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      // -windor.innerWidth < offsetWidth < 0
      let offsetWidth = Math.min(Math.max(-window.innerWidth, left + deltaX), 0)
      // 计算出滑动距离跟屏幕距离的百分比
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = 0
      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = 0
    },
    middleTouchEnd() {
      /* eslint-disable no-unused-vars */
      let offsetWidth
      let opacity
      if (!this.touch.moved) {
        return
      }
      if (this.currentShow === 'cd') {
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth
          opacity = 0
          this.currentShow = 'lyric'
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else {
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      const time = 300
      this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
      this.$refs.middleL.style.opacity = opacity
      this.$refs.middleL.style[transitionDuration] = `${time}ms`
      this.touch.initiated = false
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN',
      setPlayingState: 'SET_PLAYING_STATE'
    }),
    ...mapActions([
      'savePlayHistory'
    ])
  },
  watch: {
    // 当currentSong发生变化时就应该播放音乐
    currentSong(newSong, oldSong) {
      if (!newSong.id) {
        return
      }
      // 解决切换播放模式时触发currentSong的变化
      if (newSong.id === oldSong.id) {
        return
      }
      // 让上一首歌词不要播放
      if (this.currentLyric) {
        this.currentLyric.stop()
        this.currentTime = 0
        this.playingLyric = ''
        this.currentLineNum = 0
      }
      // 加一个定时器为了解决后台播放完成不了执行不了js
      clearTimeout(this.timer)
      // 保证里面的逻辑只执行一次
      this.timer = setTimeout(() => {
        this.$refs.audio.play()
        this.getLyric()
      }, 1000)
    },
    // 监听playing的状态，及时播放暂停音乐
    playing(newPlaying) {
      this.$nextTick(() => {
        const audio = this.$refs.audio
        newPlaying ? audio.play() : audio.pause()
      })
    }
  },
  components: {
    progressBar,
    progressCircle,
    scroll,
    playlist
  }
}
</script>
<style lang="stylus" scoped>
@import '~common/stylus/variable'
@import '~common/stylus/mixin'

.player
  .normal-player
    &.normal-enter, &.normal-leave-to
      opacity: 0
      .top
        transform: translate3d(0, -100px, 0)
      .bottom
        transform: translate3d(0, 100px, 0)
    &.normal-enter-active, &.normal-leave-acitve
      transition: all 0.3s
      .top, .bottom
        transition: all 0.3s cubic-bezier(0.86, 0.18, 0.82, 1.32)
    position: fixed
    left: 0
    right: 0
    top: 0
    bottom: 0
    z-index: 150
    background: $color-background
    .background
      position: absolute
      top: 0
      bottom: 0
      left: 0
      z-index: -1
      opacity: 0.6
      width: 100%
      height: 100%
      filter: blur(20px)
    .top
      position: relative
      margin-bottom: 25px
      .back
        position: absolute
        top: 0
        left: 6px
        z-index: 50
        .icon-back
          display: block
          padding: 9px
          font-size: 22px
          color: #ffcd32
          transform: rotate(-90deg)
      .title
        text-align: center
        font-size: 18px
        line-height: 40px
        width: 70%
        margin: 0 auto
        no-wrap()
        color: #fff
      .subtitle
        font-size: 14px
        line-height: 20px
        text-align: center
        color: #fff
    .middle
      position: absolute
      top: 80px
      bottom: 170px
      left: 0
      width: 100%
      font-size: 0
      white-space: nowrap
      .middle-l
        display: inline-block
        vertical-align: top
        position: relative
        width: 100%
        height: 0
        padding-top: 80%
        .cd-wrapper
          position: absolute
          top: 0
          left: 10%
          width: 80%
          height: 100%
          .cd
            width: 100%
            height: 100%
            border-radius: 50%
            &.play
              animation: rotate 20s linear infinite
            &.pause
              animation-play-state: paused
            .image
              position: absolute
              top: 0
              left: 0
              width: 100%
              height: 100%
              box-sizing: border-box
              border-radius: 50%
              border: 10px solid hsla(0, 0%, 100%, 0.1)
        .playing-lyric-wrapper
          width: 80%
          margin: 30px auto 0
          overflow: hidden
          text-align: center
          .playing-lyric
            height: 20px
            line-height: 20px
            font-size: 14px
            color: hsla(0, 0%, 100%, 0.5)
      .middle-r
        display: inline-block
        vertical-align: top
        width: 100%
        height: 100%
        overflow: hidden
        .lyric-wrapper
          width: 80%
          margin: 0 auto
          overflow: hidden
          text-align: center
          .text
            line-height: 32px
            color: $color-text-l
            font-size: $font-size-medium
            &.current
              color: $color-text
    .bottom
      position: absolute
      bottom: 50px
      width: 100%
      .dot-wrapper
        text-align: center
        font-size: 0
        .dot
          display: inline-block
          vertical-align: middle
          margin: 0 4px
          border-radius: 50%
          width: 8px
          height: 8px
          background: $color-text-l
          &.active
            width: 20px
            border-radius: 5px
            background: $color-text-ll
      .progress-wrapper
        display: flex
        align-items: center
        width: 80%
        margin: 0 auto
        padding: 10px 0
        .time
          flex: 0 0 30px
          color: $color-text
          font-size: $font-size-small
          line-height: 30px
          width: 30px
          &.time-l
            text-align: left
          &.time-r
            text-align: right
        .progress-bar-wrapper
          flex: 1
      .operators
        display: flex
        align-items: center
        .icon
          display: inline-block
          flex: 1
          &.disable
            color: $color-theme-d
          i
            font-size: 30px
          &.icon-left
            text-align: right
          &.icon-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          &.icon-right
            touch-action: none
            text-align: left
  .mini-player
    display: flex
    position: fixed
    align-items: center
    left: 0
    bottom: 0
    z-index: 180
    width: 100%
    height: 60px
    background: #333
    &.mini-enter-active, &.mini-leave-active
      transition: all 0.4s
    &.mini-enter, &.mini-leave-to
      opacity: 0
    .icon
      flex: 0 0 40px
      width: 40px
      height: 40px
      padding: 0 10px 0 20px
      .imgWrapper
        height: 100%
        width: 100%
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
    .text
      flex: 1
      display: flex
      flex-direction: column
      justify-content: center
      line-height: 20px
      overflow: hidden
      .name
        margin-bottom: 2px
        font-size: $font-size-medium
        color: $color-text
        no-wrap()
      .desc
        font-size: $font-size-small
        color: $color-text-d
        no-wrap()
    .control
      flex: 0 0 30px
      width: 30px
      padding: 0 10px
      .icon-play-mini, .icon-pause-mini, .icon-playlist
        font-size: 30px
        color: $color-theme-d
      .icon-mini
        font-size: 32px
        position: absolute
        left: 0
        top: 0
  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>
